import Vue from 'vue'
import VueRouter from 'vue-router'
import Cookie from 'cookie_js'

import admin from './admin'
import user from './user'
import loginBody from '@/components/login/loginBody'
import userLogin from '@/components/login/userLogin'
import adminLogin from '@/components/login/adminLogin'
import findUserPassword from '@/components/login/findUserPassword'
import sign from '@/components/login/sign'

Vue.use(VueRouter)

let router = new VueRouter({
	mode: "history",
	routes: [{
			path: '/login/',
			name: 'loginBody',
			components: {
				addComName: loginBody
			},
			children: [{
					path: "userLogin",
					name: "userLogin",
					components: {
						loginv: userLogin
					},
				},
				{
					path: "adminLogin",
					name: "adminLogin",
					components: {
						loginv: adminLogin
					},
				},
				{
					path: "findUserPassword",
					name: "findUserPassword",
					components: {
						loginv: findUserPassword
					},
				},
				{
					path: "sign",
					name: "sign",
					components: {
						loginv: sign
					},
				},
			]
		},
		{
			path: '/',
			name: 'MainHome',
			redirect: {
				name: 'userIndex'
			},
		},
		admin.admainurl,

		user.userurl,
	]
})

router.beforeEach((to, from, next) => {
	if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
		if (Cookie.get("token")) { //判断本地是否存在access_token
			localStorage.setItem("token", localStorage.getItem("Authorization"))
			next();
		} else {

			if (to.path === '/login/userLogin' || to.path === '/login/adminLogin') {
				next();
			} else {
				next({
					path: '/login/userLogin'
				})
			}
		}

	} else {
		next();
	}
	/*如果本地 存在 token 则 不允许直接跳转到 登录页面*/
	if (to.fullPath == "/admin" || to.fullPath == '/user') {
		if (Cookie.get("token")) {
			next({
				path: to.fullPath
			});
		} else {
			next();
		}
	}
});

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
	if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
	return originalPush.call(this, location).catch(err => err)
}

export default router
